package com.siants.batch;/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author yanxin
 * @create 2018/9/5
 * @since 1.0.0
 */

import com.siants.dao.Comtrx;
import com.siants.dao.Person;
import com.siants.itemprocessor.ComtrxItemProcessor;
import com.siants.itemprocessor.ComtrxMapper;
import com.siants.itemprocessor.PersonItemProcessor;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider;
import org.springframework.batch.item.database.JdbcBatchItemWriter;
import org.springframework.batch.item.database.builder.JdbcBatchItemWriterBuilder;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.FlatFileItemWriter;
import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder;
import org.springframework.batch.item.file.mapping.*;
import org.springframework.batch.item.file.transform.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.*;
import org.springframework.util.ResourceUtils;

import javax.sound.midi.Soundbank;
import javax.sql.DataSource;
import java.io.FileNotFoundException;
import java.net.MalformedURLException;

/**
 * Created by yanxin on 2018/9/5.
 */
@Configuration
@EnableBatchProcessing
public class BatchTest {

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;


    @Bean
    public FlatFileItemReader<Comtrx> reader() {
        /*return new FlatFileItemReaderBuilder<Person>()
                .name("unionpayItemReader")
                .resource(new ClassPathResource("20180903_01_AC_COMTRX"))
                .delimited()
                .names(new String[]{"firstName", "lastName"})
                .fieldSetMapper(new PassThroughFieldSetMapper().mapFieldSet())
                .build();*/
        /*DefaultLineMapper<Comtrx> lineMapper = new DefaultLineMapper<Comtrx>() {
            {
                setLineTokenizer(new DelimitedLineTokenizer() {
                    {
                        setNames(new String[]{"a", "b","c","d","e","f","g","h"});

                    }
                });
                setFieldSetMapper(new BeanWrapperFieldSetMapper<Comtrx>() {
                    {
                        setTargetType(Comtrx.class);
                    }
                });
            }
        };

        System.out.println("测试 ");
        //使用FlatFileItemReader读取文件
        FlatFileItemReader<Comtrx> reader = new FlatFileItemReader<>();
        reader.setResource(new ClassPathResource("20180903_01_AC_COMTRX"));
        reader.setLineMapper(lineMapper);
        return reader;
        */

        System.out.println("测试 ");
        /*DefaultLineMapper<Comtrx> lineMapper = new DefaultLineMapper<Comtrx>();
        FixedLengthTokenizer fixedLengthTokenizer = new FixedLengthTokenizer();

        fixedLengthTokenizer.setColumns(new Range[] {
                new Range(1, 4),
                new Range(6, 21),
                new Range(23, 37),
                new Range(39, 44),
                new Range(46, 53),
                new Range(55, 70),
                new Range(72, 86),
                new Range(88, 102)//,
                //new Range(105, 127)
        });
        fixedLengthTokenizer.setNames(new String[]{"a","b","c","d","e","f","g","h"});
        lineMapper.setLineTokenizer(fixedLengthTokenizer);
        lineMapper.setFieldSetMapper(new ComtrxMapper());
        //使用FlatFileItemReader读取文件
        FlatFileItemReader<Comtrx> reader = new FlatFileItemReader<Comtrx>();
        reader.setResource(new FileSystemResource("20180904_01_AC_COMTRX"));
        reader.setLineMapper(lineMapper);*/
        /*reader.open(new ExecutionContext());
        try {
            Comtrx comtrx = reader.read();
        } catch (Exception e) {
            e.printStackTrace();
        }*/

        FlatFileItemReader<Comtrx> reader = new FlatFileItemReader<>();
        reader.setResource(new ClassPathResource("20180904_01_AC_COMTRX"));
        DefaultLineMapper<Comtrx> lineMapper = new DefaultLineMapper<Comtrx>();
        DelimitedLineTokenizer delimitedLineTokenizer = new DelimitedLineTokenizer();
        delimitedLineTokenizer.setNames(new String[]{"a","b","c","d","e","f","g","h"});
        delimitedLineTokenizer.setDelimiter(" ");
        lineMapper.setLineTokenizer(delimitedLineTokenizer);
        lineMapper.setFieldSetMapper(new ComtrxMapper());
        reader.setLineMapper(lineMapper);
        /*reader.open(new ExecutionContext());
        try {
            reader.read();
        } catch (Exception e) {
            e.printStackTrace();
        }*/
        return reader;
    }

    @Bean
    public ComtrxItemProcessor processor() {
        System.out.println("22");
        return new ComtrxItemProcessor();
    }

    @Bean
    public FlatFileItemWriter<Comtrx> writer() {
        /*return new JdbcBatchItemWriterBuilder<Person>()
                .itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>())
                .sql("INSERT INTO people (first_name, last_name) VALUES (:firstName, :lastName)")
                .dataSource(dataSource)
                .build();*/
        //return null;
        FlatFileItemWriter<Comtrx> writer = new FlatFileItemWriter<>();
        //writer.setResource(new FilePathResource("/20180904_01_AC_COMTRX.txt"));
        // 项目resources资源目录 前提是有该文件
        //writer.setResource(new ClassPathResource("201809053_01_AC_COMTRX"));
        // 系统根目录 D:
        //writer.setResource(new FileSystemResource("/20180904_01_AC_COMTRX.txt"));

        // 系统盘根目录 D:
        //writer.setResource(new PathResource("/20180904_01_AC_COMTRX.txtpath"));

          /*try {
            writer.setResource(new FileUrlResource("/20180904_01_AC_COMTRX.txt"));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }*/

        // Intellij开发时，需要修改working directory 为$MODULE_DIR$
        writer.setResource(new FileSystemResource("src/main/resources/20180904_01_AC_COMTRX.txtsys"));



        writer.setLineAggregator(new PassThroughLineAggregator<Comtrx>());
        return writer;

    }

    // tag::jobstep[]
    @Bean
    public Job importUserJob(JobCompletionNotificationListener listener, Step step1) {
        return jobBuilderFactory.get("importUserJob")
                .incrementer(new RunIdIncrementer())
                .listener(listener)
                .flow(step1)
                .end()
                .build();
    }

    @Bean
    public Step step1(FlatFileItemWriter<Comtrx> writer) {
       /* return stepBuilderFactory.get("step1")
                .<Person, Person> chunk(10)
                //.reader(reader())
                //.build()
                .processor(processor())
                //.writer(writer)
                .build();*/
       return stepBuilderFactory.get("step1")
               .<Comtrx, Comtrx>chunk(10)
               .reader(reader())
               //.stream(fileItemReader())
               //.stream(fileItemWriter())
               .processor(processor())
               .writer(writer)
               .build();
    }


}
